package com.zwj.service.impl;

import com.zwj.bo.*;
import com.zwj.dto.SelectTeamQuery;
import com.zwj.dto.SelectTeamStudentQuery;
import com.zwj.entity.TeamInfoEntity;
import com.zwj.entity.TeamMemberInfoEntity;
import com.zwj.entity.UserEntity;
import com.zwj.enums.ValidEnum;
import com.zwj.enums.YesOrNoEnum;
import com.zwj.mapper.CommonMapper;
import com.zwj.mapper.TeamMapper;
import com.zwj.service.TeamService;
import com.zwj.utils.DataCheckUtils;
import com.zwj.utils.DateUtils;
import com.zwj.utils.PaginationUtils;
import com.zwj.vo.PaginationDate;
import com.zwj.vo.QueryReturnDate;
import com.zwj.vo.Result;
import com.zwj.vo.SelectTeamVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TeamServiceImpI implements TeamService {
    private final TeamMapper teamMapper;
    private final CommonMapper commonMapper;
    public TeamServiceImpI(TeamMapper teamMapper,CommonMapper commonMapper) {
        this.teamMapper = teamMapper;
        this.commonMapper = commonMapper;
    }
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public synchronized Result addTeam(TeamBo teamBo, UserEntity userEntity) {
        DataCheckUtils.isNotBlank(teamBo.getTeamName(), "项目组名称不能为空!");
        String teamName = commonMapper.getTeamByName(teamBo.getTeamName());
        if(teamName!=null){
            return Result.error("项目组名称重复");
        }
        TeamInfoEntity  teamInfoEntity = new TeamInfoEntity();
        teamInfoEntity.setTeamName(teamBo.getTeamName());
        teamInfoEntity.setIsGraduation(YesOrNoEnum.NO.getKey());
        teamInfoEntity.setDelFlag(ValidEnum.EFFECTIVE.getKey());
        teamInfoEntity.setCreateBy(userEntity.getId());
        teamInfoEntity.setCreateTime(DateUtils.getCurrentTime());
        teamInfoEntity.setUpdateBy(userEntity.getId());
        teamInfoEntity.setUpdateTime(DateUtils.getCurrentTime());
        int row = teamMapper.insert(teamInfoEntity);
        //判断插入结果
        if (row == 0) {
            return Result.error("添加分组失败");
        }
        return Result.success();
    }

    @Override
    public Result selectTeam(SelectTeamBo selectTeamBo) {
       /* List<SelectTeamVo> teamInfoEntities = teamMapper.selectTeam(selectTeamBo);
        if(teamInfoEntities.size()==0){
            *//*SelectTeamBo selectTeamVo = new SelectTeamBo();
            teamInfoEntities.add(selectTeamVo);*//*
            return Result.success(teamInfoEntities);
            //return Result.success("查询结果为空");
        }
        return Result.success(teamInfoEntities);*/
        int number = selectTeamBo.getNumber();
        int page = selectTeamBo.getPage();
        //DataCheckUtils.isNotBlank(selectTeamStudentBo.getIsGraduation(), "项目组是否结业不能为空!");
        //DataCheckUtils.isValid(YesOrNoEnum.getEnumValue(selectTeamStudentBo.getIsGraduation()) != null,"项目组是否结业的状态值不存在");
        DataCheckUtils.isValid(PaginationUtils.isPagingParameters(selectTeamBo.getNumber(), selectTeamBo.getPage()), "分页参数错误!");
        selectTeamBo.setPage(PaginationUtils.getPageIndex(page, number));
        List<Object> result = teamMapper.selectTeam(new SelectTeamQuery(PaginationUtils.getPageIndex(page,number),number,selectTeamBo.getTeamName(),selectTeamBo.getTeamInfoId(),selectTeamBo.getIsGraduation()));
        int sum = ((List<Integer>) result.get(1)).get(0);
        List<SelectTeamVo> selectTeamVos = (List<SelectTeamVo>) result.get(0);
        PaginationDate paginationDate = PaginationUtils.getPaginationDate(number, page, sum);
        //记录总数为0
        if (sum == 0) {
            SelectTeamVo selectTeamVo = new SelectTeamVo();
            selectTeamVos.add(selectTeamVo);
            return Result.success(new QueryReturnDate(paginationDate, selectTeamVos));
        }
        return Result.success(new QueryReturnDate(paginationDate, selectTeamVos));
    }

    @Override
    public Result selectTeamStudent(SelectTeamStudentBo selectTeamStudentBo) {
        int number = selectTeamStudentBo.getNumber();
        int page = selectTeamStudentBo.getPage();
        //DataCheckUtils.isNotBlank(selectTeamStudentBo.getIsGraduation(), "项目组是否结业不能为空!");
        //DataCheckUtils.isValid(YesOrNoEnum.getEnumValue(selectTeamStudentBo.getIsGraduation()) != null,"项目组是否结业的状态值不存在");
        DataCheckUtils.isValid(PaginationUtils.isPagingParameters(selectTeamStudentBo.getNumber(), selectTeamStudentBo.getPage()), "分页参数错误!");
        selectTeamStudentBo.setPage(PaginationUtils.getPageIndex(page, number));
        List<Object> result = teamMapper.selectTeamStudent(new SelectTeamStudentQuery(PaginationUtils.getPageIndex(page, number),number,selectTeamStudentBo.getTeamInfoId(),selectTeamStudentBo.getTeamName(),selectTeamStudentBo.getUserNo(),selectTeamStudentBo.getName(),selectTeamStudentBo.getCollegesId(),selectTeamStudentBo.getMajorId(),selectTeamStudentBo.getYearInfoId(),selectTeamStudentBo.getClassBaseInfoId(),selectTeamStudentBo.getIsGraduation(),selectTeamStudentBo.getClassIsGraduation()));
        int sum = ((List<Integer>) result.get(1)).get(0);
        List<SelectTeamStudentBo> selectTeamStudentBos = (List<SelectTeamStudentBo>) result.get(0);
        PaginationDate paginationDate = PaginationUtils.getPaginationDate(number, page, sum);
        //记录总数为0
        if (sum == 0) {
            SelectTeamStudentBo selectTeamStudentVo = new SelectTeamStudentBo();
            selectTeamStudentBos.add(selectTeamStudentVo);
            return Result.success(new QueryReturnDate(paginationDate, selectTeamStudentBos));
        }
        //当前页大于总页数
        if (PaginationUtils.isValid(paginationDate))
            return Result.error("当前页大于总页数");
        return Result.success(new QueryReturnDate(paginationDate, selectTeamStudentBos));
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public synchronized Result addTeamStudent(AddTeamStudentBo addTeamStudentBo, UserEntity userEntity) {
        //数据校验
        DataCheckUtils.isNotBlank(addTeamStudentBo.getId(), "项目组ID不能为空!");
        DataCheckUtils.isValid(addTeamStudentBo.getStudentId()!=null&&addTeamStudentBo.getStudentId().length!=0, "学生ID不能为空!");
        TeamInfoEntity teamInfoEntity = commonMapper.getTeamByIdGraduation(addTeamStudentBo.getId());
        if(teamInfoEntity==null){
            return Result.error("项目组不存在或已经结业");
        }
        for(String studentId :addTeamStudentBo.getStudentId()){
            if(commonMapper.getClassStudentById(studentId)==null){
                return Result.error("学生不存在");
            }
        }
        for(String studentId :addTeamStudentBo.getStudentId()){
            if(commonMapper.getTeamStudentById(studentId)!=null){
                return Result.error("学生存在于其他项目组，请使用更新功能");
            }
        }
        TeamMemberInfoEntity teamMemberInfoEntity = new TeamMemberInfoEntity();
        teamMemberInfoEntity.setTeamInfoId(addTeamStudentBo.getId());
        teamMemberInfoEntity.setDelFlag(ValidEnum.EFFECTIVE.getKey());
        teamMemberInfoEntity.setCreateBy(userEntity.getId());
        teamMemberInfoEntity.setCreateTime(DateUtils.getCurrentTime());
        teamMemberInfoEntity.setUpdateBy(userEntity.getId());
        teamMemberInfoEntity.setUpdateTime(DateUtils.getCurrentTime());
        for(String studentId :addTeamStudentBo.getStudentId()){
            teamMemberInfoEntity.setStudentId(studentId);
            if(teamMapper.addTeamStudent(teamMemberInfoEntity)==0){
                return Result.error("添加学生到项目组失败");
            }
        }
        return Result.success();
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public synchronized Result setTeamStudentLeader(SetTeamStudentLeaderBo setTeamStudentLeaderBo, UserEntity userEntity) {
        DataCheckUtils.isNotBlank(setTeamStudentLeaderBo.getStudentId(), "学生ID不能为空!");
        DataCheckUtils.isNotBlank(setTeamStudentLeaderBo.getTeamInfoId(), "项目组ID不能为空!");
        DataCheckUtils.isNotBlank(setTeamStudentLeaderBo.getIsTeamLeader(), "当前是否组长不能为空!");
        String  id = teamMapper.selectTeamStudentByIds(setTeamStudentLeaderBo);
        if(id==null){
            return Result.error("该项目或学生不存在");
        }
        TeamMemberInfoEntity teamMemberInfoEntity = new TeamMemberInfoEntity();
        teamMemberInfoEntity.setUpdateBy(userEntity.getId());
        teamMemberInfoEntity.setUpdateTime(DateUtils.getCurrentTime());
        String teamLeader = "0";
        if(setTeamStudentLeaderBo.getIsTeamLeader().equals("0")){
            teamLeader = "1";
            String  LeaderId = teamMapper.selectTeamStudentLeader(setTeamStudentLeaderBo.getTeamInfoId());
            if(LeaderId!=null){
                teamMemberInfoEntity.setIsTeamLeader("0");
                teamMemberInfoEntity.setId(LeaderId);
                if(teamMapper.setTeamStudentLeader(teamMemberInfoEntity)==0){
                    return Result.error("取消原项目组长失败");
                }
            }
        }
        teamMemberInfoEntity.setIsTeamLeader(teamLeader);
        teamMemberInfoEntity.setId(id);
        if(teamMapper.setTeamStudentLeader(teamMemberInfoEntity)==0){
            return Result.error("设置取消组长失败");
        }
        return Result.success();
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public  Result deleteTeamStudent(DeleteTeamStudentBo deleteTeamStudentBo, UserEntity userEntity) {
        DataCheckUtils.isValid(deleteTeamStudentBo.getStudentId().length!=0, "学生ID不能为空!");
        for(String studentId : deleteTeamStudentBo.getStudentId()){
            String isGraduation =teamMapper.getTeamByStudentId(studentId);
            if(isGraduation==null){
                return Result.error("学生不存在");
            }
            if(isGraduation.equals(YesOrNoEnum.YES.getKey())){
                return Result.error("项目组已经结业，学生不能删除");
            }
        }
        TeamMemberInfoEntity teamMemberInfoEntity = new TeamMemberInfoEntity();
        teamMemberInfoEntity.setUpdateBy(userEntity.getId());
        teamMemberInfoEntity.setUpdateTime(DateUtils.getCurrentTime());
        teamMemberInfoEntity.setDelFlag(ValidEnum.INVALID.getKey());
        for(String studentId : deleteTeamStudentBo.getStudentId()){
            teamMemberInfoEntity.setStudentId(studentId);
            if(teamMapper.deleteTeamStudentById(teamMemberInfoEntity)==0){
                return Result.error("删除学生失败");
            }
        }
        return Result.success();
    }

    @Override
    public synchronized Result updateTeam(SelectTeamBo selectTeamBo, UserEntity userEntity) {
        DataCheckUtils.isNotBlank(selectTeamBo.getTeamInfoId(), "项目组id不能为空!");
        DataCheckUtils.isNotBlank(selectTeamBo.getTeamName(), "项目组名称不能为空!");
        DataCheckUtils.isNotBlank(selectTeamBo.getIsGraduation(), "是否结业不能为空!");
        DataCheckUtils.isValid(YesOrNoEnum.getEnumValue(selectTeamBo.getIsGraduation()) != null,"是否结业的状态值不存在");
        TeamInfoEntity teamInfo = commonMapper.getTeamById(selectTeamBo.getTeamInfoId());
        if(teamInfo==null){
            return Result.error("项目组不存在");
        }
        String teamName = commonMapper.getTeamByName(selectTeamBo.getTeamName());
        if(teamName!=null && !teamName.equals(teamInfo.getTeamName())){
            return Result.error("项目组名称重复");
        }

        TeamInfoEntity  teamInfoEntity = new TeamInfoEntity();
        teamInfoEntity.setTeamName(selectTeamBo.getTeamName());
        teamInfoEntity.setIsGraduation(selectTeamBo.getIsGraduation());
        teamInfoEntity.setId(selectTeamBo.getTeamInfoId());
        teamInfoEntity.setUpdateBy(userEntity.getId());
        teamInfoEntity.setUpdateTime(DateUtils.getCurrentTime());
        int row = teamMapper.updateById(teamInfoEntity);
        //判断结果
        if (row == 0) {
            return Result.error("修改分组失败");
        }
        return Result.success();
    }

    @Override
    public  Result deleteTeam(DeleteTeamBo deleteTeamBo, UserEntity userEntity) {
        DataCheckUtils.isNotBlank(deleteTeamBo.getTeamInfoId(), "项目组id不能为空!");
        TeamInfoEntity teamInfo = commonMapper.getTeamById(deleteTeamBo.getTeamInfoId());
        if(teamInfo==null){
            return Result.error("项目组不存在");
        }
        if(teamInfo.getIsGraduation().equals(YesOrNoEnum.YES.getKey())){
            return Result.error("项目组已经结业不能删除");
        }
        TeamInfoEntity  teamInfoEntity = new TeamInfoEntity();
        teamInfoEntity.setDelFlag(ValidEnum.INVALID.getKey());
        teamInfoEntity.setId(deleteTeamBo.getTeamInfoId());
        teamInfoEntity.setUpdateBy(userEntity.getId());
        teamInfoEntity.setUpdateTime(DateUtils.getCurrentTime());
        int row = teamMapper.updateById(teamInfoEntity);
        //判断结果
        if (row == 0) {
            return Result.error("删除分组失败");
        }
        return Result.success();
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public synchronized Result setStudentTeam(SetStudentTeamBo setStudentTeamBo, UserEntity userEntity) {
        DataCheckUtils.isNotBlank(setStudentTeamBo.getTeamInfoId(), "项目组ID不能为空!");
        DataCheckUtils.isValid(setStudentTeamBo.getStudentId().length!=0, "学生ID不能为空!");
        TeamInfoEntity teamInfo = commonMapper.getTeamById(setStudentTeamBo.getTeamInfoId());
        if(teamInfo==null){
            return Result.error("项目组不存在");
        }
        if(teamInfo.getIsGraduation().equals(YesOrNoEnum.YES.getKey())){
            return Result.error("目标项目组已经结业，不能更换项目组");
        }
        for(String studentId : setStudentTeamBo.getStudentId()){
            String isGraduation =teamMapper.getTeamByStudentId(studentId);
            if(isGraduation==null){
                return Result.error("学生不存在");
            }
            if(isGraduation.equals(YesOrNoEnum.YES.getKey())){
                return Result.error("项目组已经结业，学生信息不能更改");
            }
        }
        TeamMemberInfoEntity teamMemberInfoEntity = new TeamMemberInfoEntity();
        teamMemberInfoEntity.setUpdateBy(userEntity.getId());
        teamMemberInfoEntity.setUpdateTime(DateUtils.getCurrentTime());
        teamMemberInfoEntity.setIsTeamLeader("1");
        teamMemberInfoEntity.setTeamInfoId(setStudentTeamBo.getTeamInfoId());
        for(String studentId : setStudentTeamBo.getStudentId()){
            teamMemberInfoEntity.setStudentId(studentId);
            if(teamMapper.setStudentTeam(teamMemberInfoEntity)==0){
                return Result.error("更新学生失败");
            }
        }
        return Result.success();
    }
}
